package com.woniu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.core.exception.order.OrderException;
import com.woniu.core.exception.order.OrderExceptionCode;
import com.woniu.core.util.PageInfo;
import com.woniu.core.util.Result;
import com.woniu.order.client.GymServerClient;
import com.woniu.order.client.dto.GymBaseDto;
import com.woniu.order.config.AlipayConfiguration;
import com.woniu.order.dao.InOrderLogMapper;
import com.woniu.order.dao.TInOrderMapper;
import com.woniu.order.dto.AddGymEnterOrderDto;
import com.woniu.order.dto.AdminInOrderSearchDto;
import com.woniu.order.dto.AdminOrderSearchDto;
import com.woniu.order.form.AddGymEnterOrderForm;
import com.woniu.order.form.AdminInOrderSearchForm;
import com.woniu.order.form.AlipayForm;
import com.woniu.order.form.OrderNumForm;
import com.woniu.order.model.InOrderLog;
import com.woniu.order.model.TCourseOrder;
import com.woniu.order.model.TInOrder;
import com.woniu.order.service.TInOrderService;
import com.woniu.order.util.AlipayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年04月02日
 */
@Service
public class TInOrderServiceImpl extends ServiceImpl<TInOrderMapper, TInOrder> implements TInOrderService {
    @Resource
    private InOrderLogMapper inOrderLogMapper;
    @Resource
    private GymServerClient gymServerClient;
    @Resource
    private TInOrderMapper tInOrderMapper;
    @Resource
    private AlipayUtil alipayUtil;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private AlipayConfiguration alipayConfiguration;
    @Override
    public AddGymEnterOrderDto addGymEnterOrder(AddGymEnterOrderForm form) {
        TInOrder tInOrder = BeanUtil.toBean(form, TInOrder.class);
        Snowflake snowflake = new Snowflake();
        tInOrder.setInOrderNum(snowflake.nextIdStr());
        tInOrder.setOrderMoney(BigDecimal.valueOf(5000));
        tInOrder.setOrderDate(LocalDateTime.now());
        tInOrder.setOrderState(0);
        tInOrder.setDeleteFlag(1);
        save(tInOrder);
        AddGymEnterOrderDto dto = BeanUtil.toBean(tInOrder, AddGymEnterOrderDto.class);
        //延迟消息发送
        rabbitTemplate.convertAndSend("check_gym_order_queue_delay",tInOrder.getInOrderNum());
        //新增入驻订单日志表
        InOrderLog orderLog = new InOrderLog();
        orderLog.setInOrderNum(tInOrder.getInOrderNum());
        orderLog.setLogInfo(tInOrder.getInOrderNum()+"订单已创建成功");
        orderLog.setLogUser(tInOrder.getAccountName());
        orderLog.setGymNum(tInOrder.getGymNum());
        orderLog.setLogTime(LocalDateTime.now());
        inOrderLogMapper.insert(orderLog);


        return dto;
    }

    @Override
    public String pay(OrderNumForm orderForm) throws Exception {
        Result<GymBaseDto> gymBaseResult = gymServerClient.findGymBaseByNum(orderForm.getGymNum());
        if(gymBaseResult==null){
            throw new OrderException(gymBaseResult.getMsg(),gymBaseResult.getCode());
        }
        QueryWrapper<TInOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("in_order_num",orderForm.getOrderNum()).eq("gym_num",orderForm.getOrderNum());
        TInOrder tInOrder = tInOrderMapper.selectOne(wrapper);
        if(tInOrder==null){
            throw new OrderException(OrderExceptionCode.ORDER_NOT_EXIST);
        }
       if(tInOrder.getOrderState()!=0){
           throw new OrderException(OrderExceptionCode.ORDER_HANDLE);
       }
        //组装支付参数
        AlipayForm form = new AlipayForm();
        form.setBody("场馆入驻订单支付");
        form.setMoney(tInOrder.getOrderMoney().doubleValue());
        form.setNotifyUrl("http://z835y2.natappfree.cc/order/tInOrder/notify");
        form.setReturnUrl("https://www.woniuxy.com/");
        form.setOrderNum(tInOrder.getInOrderNum());
//        form.setPayTimeBorder((int)(seconds/60));
        form.setSubject("蜗牛瑜伽馆");
        //调用支付宝支付接口
        String pay = alipayUtil.pagePay(form);
        return pay;
    }

    @Override
    public void payNotify(Map<String, String> params) throws Exception {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayConfiguration.getAlipayPublicKey(),"utf-8", "RSA2"); //调用SDK验证签名
        if(!signVerified){
            throw new Exception("验证异常");
        }
        System.out.println("验证通过");
        String orderNum = params.get("out_trade_no");
        String tradeStatus = params.get("trade_status");
        String paytime = params.get("gmt_payment");
        System.out.println("params = " + tradeStatus );


        if("TRADE_SUCCESS".equalsIgnoreCase(tradeStatus)){
            //表示用户已支付完毕
//            System.out.println("进入修改");
            TInOrder orderInfo = tInOrderMapper.selectById(orderNum);
            //判断订单状态
            if(orderInfo.getOrderState()==0){
                //订单状态为未支付，修改订单状态为已支付
                orderInfo.setOrderState(1);
                LocalDateTime localDate=LocalDateTime.parse(paytime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                orderInfo.setOrderPaytime(localDate);
                //  // 修改场馆的订单状态为已支付，店铺状态为正常
               gymServerClient.modifyGymState(orderInfo.getGymNum());

                //记录日志
                InOrderLog orderLog = new InOrderLog();
                orderLog.setInOrderNum(orderInfo.getInOrderNum());
                orderLog.setLogInfo(orderInfo.getInOrderNum()+"订单已支付成功");
                orderLog.setLogUser(orderInfo.getAccountName());
                orderLog.setGymNum(orderInfo.getGymNum());
                orderLog.setLogTime(LocalDateTime.now());
                inOrderLogMapper.insert(orderLog);
            }
        }
    }

    @Override
    public PageInfo<AdminInOrderSearchDto> adminListInOrder(AdminInOrderSearchForm form) throws Exception {
        Page<TInOrder> page = new Page<>(form.getPageNum()==null?1:form.getPageNum(),form.getPageSize()==null?10:form.getPageSize());
        QueryWrapper<TInOrder> wrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(form.getGymNum())){
            wrapper.eq("gym_num",form.getGymNum());
        }
        if(ObjectUtil.isAllNotEmpty(form.getInOrderNum())){
            wrapper.eq("in_order_num",form.getInOrderNum());
        }
        if(ObjectUtil.isAllNotEmpty(form.getOrderState())){
            wrapper.eq("order_state",form.getOrderState());
        }
        tInOrderMapper.selectPage(page,wrapper);
        List<TInOrder> list = page.getRecords();
        ArrayList<AdminInOrderSearchDto> data = new ArrayList<>();
        for (TInOrder tInOrder : list) {
            AdminInOrderSearchDto dto = BeanUtil.toBean(tInOrder, AdminInOrderSearchDto.class);
            data.add(dto);
        }
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setList(data);
        pageInfo.setPages(page.getPages());
        pageInfo.setCurrent((form.getPageNum()==null?1L:form.getPageNum()));
        pageInfo.setSize(form.getPageSize()==null?10L:form.getPageSize());
        int intValue = data.size(); // 定义一个int类型的整数
        long longValue = intValue; // 将int类型的整数赋值给long类型的变量
        pageInfo.setTotal(longValue);
        return pageInfo;
    }
}
